package controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import entity.Users;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import service.UserService;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Reference
    private UserService userService;

    /**
     * 新增用户
     *
     * @param users
     * @return
     */
    @PostMapping()
    @ResponseBody
    public String register(@RequestBody Users users) {
        System.out.println(users);
        System.out.println("注册");
        try {
            users.setCreatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:sss").format(new Date()));
            int result =0;
            if(users.getUid()>0){
                result =userService.updateUser(users);
            }else{
                result =userService.register(users);
            }
            if (result == 1) {
                return "成功";
            } else {
                return "失败";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return "失败";
        }
    }
    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @ResponseBody
    public String deleteUser(@PathVariable Integer id) {
        System.out.println("删除"+id);
        try {
            int register = userService.deleteUser(id);
            if (register == 1) {
                return "成功";
            } else {
                return "失败";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return "失败";
        }
    }

    /**
     * 查询用户
     *
     * @param username
     * @return
     */
    @GetMapping("/list")
    @ResponseBody
    public String findUsers(@RequestParam String username) throws UnsupportedEncodingException {
        //前台URL加密后 后台需要解密一次
        username = java.net.URLDecoder.decode(username,  "UTF-8");
        System.out.println("查询用户列表"+username);
        try {
            List<Users> users = userService.findUsers(username);
            return JSON.toJSONString(users);
        } catch (Exception ex) {
            ex.printStackTrace();
            return "失败";
        }
    }

    /**
     * 查询用户
     *
     * @param id
     * @return
     */
    @GetMapping("/detail/{id}")
    @ResponseBody
    public String getUser(@PathVariable Integer id) {
        System.out.println("查询用户" + id);
        try {
            Users users = userService.getUser(id);
            return JSON.toJSONString(users);
        } catch (Exception ex) {
            ex.printStackTrace();
            return "失败";
        }
    }
}
